<?php
namespace app\common\component\user_sign;

use think\Session;

class UserSignService {
	public function sign() {
		$userId = Session::get('user_id');
		$points = getParam('SIGN_POINTS');

		$today = strtotime(date('Ymd'));

		$userSignModel = UserSignModel::get($userId);
		if($userSignModel) {
			
			// 判断今天是否已经签到
			if($userSignModel -> last_time == $today) {
				return [
					'code' => -1,
					'message' => '今日已签到'
				];
			}

			// 判断是否连续签到
			if($userSignModel -> last_time + 24 * 60 *60 == $today) {
				$userSignModel -> continuity_total_day = $userSignModel -> continuity_total_day + 1;
				$userSignModel -> continuity_total_points = $userSignModel -> continuity_total_points + $points;
			}

			// 判断月连续签到
			if(date('m', $userSignModel -> last_time) == date('m', $today)) {
				$userSignModel -> month_total_day = $userSignModel -> month_total_day + 1;
				$userSignModel -> month_total_points = $userSignModel -> month_total_points + $points;
			} else {
				$userSignModel -> month_total_day = 1;
				$userSignModel -> month_total_points = $points;
			}

			$userSignModel -> total_day = $userSignModel -> total_day + 1;
			$userSignModel -> total_points = $userSignModel -> total_points + $points;

			$userSignModel -> last_points = $points;
			$userSignModel -> last_time = $today;

		} else {
			// 首次签到

			$userSignModel = new UserSignModel();
			$userSignModel -> user_id = $userId;
			$userSignModel -> username = Session::get('user_name');
			$userSignModel -> level = 1;
			$userSignModel -> continuity_total_day = 1;
			$userSignModel -> continuity_total_points = $points;
			$userSignModel -> month_total_day = 1;
			$userSignModel -> month_total_points = $points;
			$userSignModel -> total_day = 1;
			$userSignModel -> total_points = $points;
			$userSignModel -> last_points = $points;
			$userSignModel -> last_time = $today;
		}

		if($userSignModel -> save()) {
			return [
				'code' => 0,
				'message' => 'Success',
				'data' => [
					'user_id' => $userSignModel -> user_id
				],
			];
		}

		return [
			'code' => -1,
			'message' => '签单失败'
		];
	}

	public function getUserSign($user_id = null) {
    	if($user_id && $user_id > 0) {
    		$getUserSign = UserSignModel::get(['user_id' => $user_id]);
    	} else if(Session::has('user_id')) {
    		$getUserSign = UserSignModel::get(['user_id' => Session::get('user_id')]);
    	} else {
    		$getUserSign = false;
    	}

		if($getUserSign) {
			return [
				'code' => 0,
				'data' => [
					'user_sign' => $getUserSign
				]
			];
		}

		return [
			'code' => -1,
			'message' => '该用户不存在'
		];
    }
}
?>